//
//  UserManager.m
//  MiAiApp
//
//  Created by voidcat on 2017/5/22.
//  Copyright © 2017年 voidcat. All rights reserved.
//

#import "UserManager.h"
#import <UMSocialCore/UMSocialCore.h>
#import "LoginModel.h"
@implementation UserManager

SINGLETON_FOR_CLASS(UserManager);

-(instancetype)init{
    self = [super init];
    if (self) {
        //被踢下线
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(onKick)
                                                     name:KNotificationOnKick
                                                   object:nil];
    }
    return self;
}

#pragma mark ————— 三方登录 —————
-(void)login:(UserLoginType )loginType completion:(loginBlock)completion{
    [self login:loginType params:nil completion:completion];
}

#pragma mark ————— 带参数登录 —————
-(void)login:(UserLoginType )loginType params:(NSDictionary *)params completion:(loginBlock)completion{
    //友盟登录类型
    //清除登录缓存，让其每次都掉起登录页面
    [UMSocialGlobal shareInstance].isClearCacheWhenGetUserInfo = YES;

    UMSocialPlatformType platFormType;
    
    if (loginType == kUserLoginTypeQQ) {
        platFormType = UMSocialPlatformType_QQ;
    }else if (loginType == kUserLoginTypeWeChat){
        platFormType = UMSocialPlatformType_WechatSession;
    }else{
        platFormType = UMSocialPlatformType_UnKnown;
    }
    //第三方登录
    if (loginType != kUserLoginTypePwd) {
        [MBProgressHUD showActivityMessageInView:ASLocalizedString(@"授权中...")];
        [[UMSocialManager defaultManager] getUserInfoWithPlatform:platFormType currentViewController:nil completion:^(id result, NSError *error) {
            if (error) {
                [MBProgressHUD hideHUD];
                if (completion) {
                    completion(NO,error.localizedDescription);
                }
            } else {
                [MBProgressHUD hideHUD];
                UMSocialUserInfoResponse *resp = result;

//                NSDictionary *params = @{@"openid":resp.openid, @"nickname":resp.name, @"photo":resp.iconurl, @"sex":[resp.unionGender isEqualToString:ASLocalizedString(@"男")]?@1:@2, @"cityname":resp.originalResponse[@"city"], @"fr":@(loginType)};
                
                self.loginType = loginType;
                //登录到服务器
//                [self loginToServer:params completion:completion];
                [self loginToServerWidthOpenID:resp.openid completion:completion];
            }
        }];
    }else{
        [self loginToServer:params completion:^(BOOL success, NSString *des) {
            completion(success,des);
        }];
    }
}

#pragma mark - 第三方登录
-(void)loginToServerWidthOpenID:(NSString *)openid completion:(loginBlock)completion{
    [[HUDHelper sharedInstance] syncLoading:ASLocalizedString(@"登录中...")];
    NSString *url = [[CYURLUtils sharedCYURLUtils] makeURLWithC:@"login_api" A:@"auth_login"];
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [param setObject:openid forKey:@"plat_id"];
    [param setObject:[LoginModel sharedLoginModel].invite_code forKey:@"invite_code"];

    [CYNET POSTv3:url parameters:param responseCache:^(id responseObject) {
        
    } success:^(id responseObject) {
        [[HUDHelper sharedInstance] syncStopLoading];
        [MBProgressHUD hideHUD];
        [self LoginSuccess:[responseObject valueForKey:@"data"] completion:completion];
    } failure:^(NSString *error, NSInteger code) {
        
    } hasCache:NO];
}

#pragma mark ————— 手动登录到服务器 —————
-(void)loginToServer:(NSDictionary *)params completion:(loginBlock)completion{
//        [[HUDHelper sharedInstance] syncLoading:ASLocalizedString(@"登录中...")];
        NSString *url = [[CYURLUtils sharedCYURLUtils] makeURLWithC:@"login_api" A:@"do_login"];
        NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:params];
        [dic setObject:[LoginModel sharedLoginModel].invite_code forKey:@"invite_code"];

        [CYNET POST:url parameters:dic responseCache:^(id responseObject) {

        } success:^(id responseObject) {
//            [[HUDHelper sharedInstance] syncStopLoading];
            [MBProgressHUD hideHUD];
            [self LoginSuccess:responseObject completion:completion];

        } failure:^(NSString *error) {
            [[HUDHelper sharedInstance] syncStopLoading];
            [MBProgressHUD showTopTipMessage:error];
            completion(NO,error);
            
        } hasCache:NO];
}

#pragma mark ————— 自动登录到服务器 —————
-(void)autoLoginToServer:(loginBlock)completion{    
//    completion(@YES,ASLocalizedString(@"测试登录成功"));
//    [PPNetworkHelper POST:NSStringFormat(@"%@%@",URL_main,URL_user_auto_login) parameters:nil success:^(id responseObject) {
//        [self LoginSuccess:responseObject completion:completion];
//
//    } failure:^(NSError *error) {
//        if (completion) {
//            completion(NO,error.localizedDescription);
//        }
//    }];
}

#pragma mark ————— 登录成功处理 —————
-(void)LoginSuccess:(id )responseObject completion:(loginBlock)completion{
    //储存用户信息
    [UserManager sharedUserManager].curUserInfo = [UserInfo modelWithDictionary:responseObject];
    
    [[IMManager sharedIMManager] IMLogin:@"" IMPwd:@"" completion:^(BOOL success, NSString *des) {
        [MBProgressHUD hideHUD];
        if (success) {
//            [self saveUserInfo];
            self.isLogined = YES;
            //如果已经完善资料
            if([curUser.is_reg_perfect isEqualToString:@"1"])
            {
                [[UserManager sharedUserManager] saveUserInfo];
            }

            if (completion) {
                completion(YES,nil);
            }
        }else{
            if (completion) {
                
                //多登陆一次
                [[IMManager sharedIMManager] IMLogin:@"" IMPwd:@"" completion:^(BOOL success, NSString *des) {
                    [MBProgressHUD hideHUD];
                    if (success) {
                        //            [self saveUserInfo];
                        self.isLogined = YES;
                        //如果已经完善资料
                        if([curUser.is_reg_perfect isEqualToString:@"1"])
                        {
                            [[UserManager sharedUserManager] saveUserInfo];
                        }
                        
                        if (completion) {
                            completion(YES,nil);
                        }
                    }else{
                        if (completion) {
                            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:ASLocalizedString(@"IM登录超时")message:des
                                                                           delegate:nil
                                                                  cancelButtonTitle:ASLocalizedString(@"重新登录")otherButtonTitles:nil];
                            [alert show];
                            completion(NO,ASLocalizedString(@"IM登录失败"));
                        }
                        KPostNotification(KNotificationLoginStateChange, @NO);
                    }
                }];
                
                
//                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:ASLocalizedString(@"IM登录失败")//                                                                message:des
//                                                               delegate:nil
//                                                      cancelButtonTitle:NSLocalizedString(@"sure", ASLocalizedString(@"确定"))
//                                                      otherButtonTitles:nil];
//                [alert show];
//                completion(NO,ASLocalizedString(@"IM登录失败"));
            }
            KPostNotification(KNotificationLoginStateChange, @NO);
        }
    }];
    
//
//    if (ValidDict(responseObject)) {
//        if (ValidDict(responseObject[@"data"])) {
//            NSDictionary *data = responseObject[@"data"];
//            if (ValidStr(data[@"imId"]) && ValidStr(data[@"imPass"])) {
//                //登录IM
//                [[IMManager sharedIMManager] IMLogin:data[@"imId"] IMPwd:data[@"imPass"] completion:^(BOOL success, NSString *des) {
//                    [MBProgressHUD hideHUD];
//                    if (success) {
//                        self.curUserInfo = [UserInfo modelWithDictionary:data];
//                        [self saveUserInfo];
//                        self.isLogined = YES;
//                        if (completion) {
//                            completion(YES,nil);
//                        }
//                        KPostNotification(KNotificationLoginStateChange, @YES);
//                    }else{
//                        if (completion) {
//                            completion(NO,ASLocalizedString(@"IM登录失败"));
//                        }
//                        KPostNotification(KNotificationLoginStateChange, @NO);
//                    }
//                }];
//            }else{
//                if (completion) {
//                    completion(NO,ASLocalizedString(@"登录返回数据异常"));
//                }
//                KPostNotification(KNotificationLoginStateChange, @NO);
//            }
//
//        }
//    }else{
//        if (completion) {
//            completion(NO,ASLocalizedString(@"登录返回数据异常"));
//        }
//        KPostNotification(KNotificationLoginStateChange, @NO);
//    }
    
}
#pragma mark ————— 储存用户信息 —————
-(void)saveUserInfo{
    if (self.curUserInfo) {
        
        //不用YYcache了，有时候可能内存不足会被清空
        NSDictionary *dic = [self.curUserInfo modelToJSONObject];
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        [defaults setObject:dic forKey:@"cyUsefInfo"];
        [defaults synchronize];
//
//        YYCache *cache = [[YYCache alloc]initWithName:KUserCacheName];
//        NSDictionary *dic = [self.curUserInfo modelToJSONObject];
//        [cache setObject:dic forKey:KUserModelCache];
    }
    
}
#pragma mark ————— 加载缓存的用户信息 —————
-(BOOL)loadUserInfo{
    
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSDictionary *userinfo = [defaults objectForKey:@"cyUsefInfo"];
    if(userinfo)
    {
        self.curUserInfo = [UserInfo modelWithJSON:userinfo];
        return YES;
    }
    return NO;
    
//    YYCache *cache = [[YYCache alloc]initWithName:KUserCacheName];
//    NSDictionary * userDic = (NSDictionary *)[cache objectForKey:KUserModelCache];
//    NSLog(ASLocalizedString(@"加载用户缓存信息 %@:%@"),userDic,cache);
//    if (userDic) {
//        self.curUserInfo = [UserInfo modelWithJSON:userDic];
//        return YES;
//    }
    return NO;
}
#pragma mark ————— 被踢下线 —————
-(void)onKick{
    [self logout:nil];
}
#pragma mark ————— 退出登录 —————
- (void)logout:(void (^)(BOOL, NSString *))completion{
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    
    [[UIApplication sharedApplication] unregisterForRemoteNotifications];
    
//    [[NSNotificationCenter defaultCenter] postNotificationName:KNotificationLogout object:nil];//被踢下线通知用户退出直播间
    
    [[IMManager sharedIMManager] IMLogout];
    
    self.curUserInfo = nil;
    self.isLogined = NO;

//    NSDictionary *dic = [self.curUserInfo modelToJSONObject];
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
//    [defaults removePersistentDomainForName:@"cyUsefInfo"];
    [defaults removeObjectForKey:@"cyUsefInfo"];
//    [defaults setObject:dic forKey:@"cyUsefInfo"];
    [defaults synchronize];
    
//    //移除缓存
//    YYCache *cache = [[YYCache alloc]initWithName:KUserCacheName];
//    [cache removeAllObjectsWithBlock:^{
//        if (completion) {
//            completion(YES,nil);
//        }
//    }];
    
    KPostNotification(KNotificationLoginStateChange, @NO);
}
@end
